package com.music.checkpoints.common.core.security;


import com.music.checkpoints.common.config.dao.RedisConfiguration;
import com.music.checkpoints.common.entity.NationExaminee;
import com.music.checkpoints.common.service.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AccessTokenAuthenticationService {
    @Autowired
    private CacheManager cacheService;
    @Autowired
    private RedisConfiguration redisConfiguration;

    public void auth(HttpServletRequest request) {
        String token = getToken(request);
        if (!StringUtils.isEmpty(token)) {
            Authentication authentication = getAuthentication(token);
            if (authentication != null) {
                SecurityContextHolder.getContext()
                        .setAuthentication(authentication);
            }
        }
    }

    /**
     * 获取授权
     *
     * @return
     */
    private Authentication getAuthentication(String token) {
        List<GrantedAuthority> auths = new ArrayList<>();
        auths.add(new SimpleGrantedAuthority("ROLE_USER"));
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(token, null, auths);
        return authentication;
    }

    /**
     * 生成系统用户
     *
     * @return
     */
    private static NationExaminee buildUser(Map<String, String> map) {
        NationExaminee users = new NationExaminee();
        users.setRealname(map.get("realname"));
        users.setCardNum(map.get("card_num"));
        return users;
    }

    /**
     * 获取缓存中的token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(token)) {
            token = token.replaceAll("Bearer", "").trim();
            StringBuilder sb = new StringBuilder();
            sb.append(redisConfiguration.getRedisPrefix());
            sb.append(redisConfiguration.getAccessToken());
            sb.append(token);
            if (cacheService.exists(sb.toString())) {
                return token;
            } else {
                String str = redisConfiguration.getRedisPrefix() + redisConfiguration.getMonitorToken() + token;
                if (cacheService.exists(str)) {
                    return token;
                }
            }
        }
        return null;
    }
}
